// 1. 研究区域
var roi = ROI_Edge;
Map.centerObject(roi, 8);

// 2. 定义指数计算函数
function computeIndices(image) {
  var ndvi = image.normalizedDifference(['B8', 'B4']).rename('NDVI');
  var mndwi = image.normalizedDifference(['B3', 'B11']).rename('MNDWI');
  var lswi = image.normalizedDifference(['B8','B11']).rename('LSWI');
  var gcvi = image.expression('((NIR / GREEN) - 1)', {
    'NIR': image.select('B8'),
    'GREEN': image.select('B3')
  }).rename('GCVI');
  var ndsvi = image.normalizedDifference(['B11','B4']).rename('NDSVI');
  return ndvi.addBands([mndwi, lswi, gcvi, ndsvi]);
}

// 3. Sentinel-2 预处理函数
function maskAndPrepare(image) {
  var qa = image.select('QA60');
  var mask = qa.bitwiseAnd(1 << 10).eq(0).and(qa.bitwiseAnd(1 << 11).eq(0));
  return image.updateMask(mask)
              .select(['B2','B3','B4','B8','B11']) // 仅保留用到的波段
              .divide(10000)
              .copyProperties(image, image.propertyNames());
}

// 4. 定义月份列表和空图层容器
var months = ee.List.sequence(4, 10);
var imageList = months.map(function(m) {
  m = ee.Number(m);
  var start = ee.Date.fromYMD(2022, m, 1);
  var end = start.advance(1, 'month');

  var s2 = ee.ImageCollection("COPERNICUS/S2_SR_HARMONIZED")
              .filterBounds(roi)
              .filterDate(start, end)
              .filter(ee.Filter.lt('CLOUDY_PIXEL_PERCENTAGE', 10))
              .map(maskAndPrepare);

  var composite = s2.median().clip(roi);
  var indices = computeIndices(composite);

  // 重命名每个波段，加上月份后缀
  var renamed = indices.rename(
    indices.bandNames().map(function(bandName) {
      return ee.String(bandName).cat('_month').cat(m.int());
    })
  );
  
  return renamed;
});

// 5. 合并所有月份的图像为一个多波段图
var stacked = ee.Image(imageList.iterate(function(img, prev) {
  return ee.Image(prev).addBands(ee.Image(img));
}, ee.Image([])));

// 6. 导出任务设置
Export.image.toDrive({
  image: stacked.toFloat(),
  description: 'S2_Indices_2022_5x7',
  folder: 'GEE_Exports',
  fileNamePrefix: 'S2_indices_5x7bands',
  region: roi,
  scale: 10,
  crs: 'EPSG:4326',
  maxPixels: 1e13,
  fileFormat: 'GeoTIFF'
});
